/**
 * Filename: NewsActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/2 12:26
 */
package com.github.postsanf.yinian.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.NewsFragmentAdapter;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.fragment.NewsCommentFragment;
import com.github.postsanf.yinian.fragment.NewsInviteFragment;
import com.github.postsanf.yinian.fragment.NewsNoticeFragment;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;


/**
 * 忆年消息界面
 */
public class NewsActivity extends BaseActivity implements ISkinUpdate {
    private Toolbar mToolbar;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;
    private List<Fragment> fragments;
    private String type;
    private Resources mResource;
    private TextView tabtx1, tabtx2, tabtx3;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_news);
        BaseApplication.getInstance().mActivitys.add(this);
        SharedPreferences sharedPreferences = getSharedPreferences(ACTIONs.mymsg, 0);
        editor = sharedPreferences.edit();
        initView();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.news_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        mViewPager = (ViewPager) findViewById(R.id.vp_news_viewpager);
        setupViewPager();
    }

    // 初始化切换
    private void setupViewPager() {
        LayoutInflater mLayoutInflater = android.view.LayoutInflater.from(NewsActivity.this);
        mTabLayout = (TabLayout) findViewById(R.id.tl_news_tabs);
        List<String> titles = new ArrayList<>();
        titles.add("评论");
        titles.add("通知");
//        titles.add("邀请");
        List<View> Views = new ArrayList<>();
        View tabview1 = mLayoutInflater.inflate(R.layout.tablayout_view1, null);
        tabtx1 = (TextView) tabview1.findViewById(R.id.tab1_msg_num);
        Views.add(tabview1);
        View tabview2 = mLayoutInflater.inflate(R.layout.tablayout_view2, null);
        tabtx2 = (TextView) tabview2.findViewById(R.id.tab2_msg_num);
        Views.add(tabview2);
//        View tabview3 = mLayoutInflater.inflate(R.layout.tablayout_view3, null);
//        tabtx3 = (TextView) tabview3.findViewById(R.id.tab3_msg_num);
//        Views.add(tabview3);
//        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(0)).setTag(0));
//        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(1)).setTag(1));
//        mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(2)).setTag(2));
        fragments = new ArrayList<>();
        fragments.add(new NewsCommentFragment());
        fragments.add(new NewsNoticeFragment());
//        fragments.add(new NewsInviteFragment());
        NewsFragmentAdapter adapter =
                new NewsFragmentAdapter(getSupportFragmentManager(), fragments, titles);
        mViewPager.setAdapter(adapter);
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setupWithViewPager(mViewPager);
        //mTabLayout.setTabsFromPagerAdapter(adapter);
        mTabLayout.getTabAt(0).setCustomView(Views.get(0));
        mTabLayout.getTabAt(1).setCustomView(Views.get(1));
//        mTabLayout.getTabAt(2).setCustomView(Views.get(2));
        SharedPreferences preferences = getSharedPreferences(
                ACTIONs.mymsg, 0);
        int commentnum = preferences.getInt(ACTIONs.commentnum, 0);
        if (commentnum > 0) {
            tabtx1.setVisibility(View.VISIBLE);
            tabtx1.setText(String.valueOf(commentnum));
        } else {
            tabtx1.setVisibility(View.GONE);
        }
        int notifnum = preferences.getInt(ACTIONs.notifynum, 0);
        if (notifnum > 0) {
            tabtx2.setVisibility(View.VISIBLE);
            tabtx2.setText(String.valueOf(notifnum));
        } else {
            tabtx2.setVisibility(View.GONE);
        }
//        int invitenum = preferences.getInt(ACTIONs.invitenum, 0);
//        if (invitenum > 0) {
//            tabtx3.setVisibility(View.VISIBLE);
//            tabtx3.setText(String.valueOf(invitenum));
//        } else {
//            tabtx3.setVisibility(View.GONE);
//        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                editor.putBoolean(ACTIONs.commentbb, false);
                editor.putInt(ACTIONs.commentnum, 0);
                editor.commit();
                tabtx1.setVisibility(View.GONE);
                sendBroadcast(new Intent(ACTIONs.actionMymessageNums));
            }
        }, 1000);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        editor.putBoolean(ACTIONs.commentbb, false);
                        editor.putInt(ACTIONs.commentnum, 0);
                        editor.commit();
                        tabtx1.setVisibility(View.GONE);
                        break;
                    case 1:
                        editor.putBoolean(ACTIONs.notifybb, false);
                        editor.putInt(ACTIONs.notifynum, 0);
                        editor.commit();
                        tabtx2.setVisibility(View.GONE);
                        break;
//                    case 2:
//                        editor.putBoolean(ACTIONs.invitebb, false);
//                        editor.putInt(ACTIONs.invitenum, 0);
//                        editor.commit();
//                        tabtx3.setVisibility(View.GONE);
//                        break;
                }
                sendBroadcast(new Intent(ACTIONs.actionMymessageNums));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_news, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_clear:
                type = "";
                String tip = "";
                switch (mViewPager.getCurrentItem()) {
                    case 0:
                        type = "comment";
                        tip = "评论";
                        break;
                    case 1:
                        type = "notification";
                        tip = "通知";
                        break;
//                    case 2:
//                        type = "invite";
//                        tip = "邀请";
//                        break;
                }
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
                builder.setCancelable(false);
                final android.support.v7.app.AlertDialog dlg = builder.create();
                dlg.show();
                Window window = dlg.getWindow();
                window.setContentView(R.layout.pub_dialog);
                window.setBackgroundDrawableResource(R.color.transparent);
                WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
                layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
                dlg.getWindow().setAttributes(layout);
                TextView tt = (TextView) window.findViewById(R.id.pp_title);
                tt.setText("提示");
                TextView content = (TextView) window.findViewById(R.id.pp_content);
                content.setText("确定要清空" + tip + "消息吗？");
                TextView cancel = (TextView) window
                        .findViewById(R.id.btn_cancel);
                cancel.setText("取消");
                cancel.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        dlg.cancel();
                    }
                });
                final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
                ok.setText("确定");
                ok.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        clearAll(type);
                        dlg.cancel();
                    }
                });
                break;
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void clearAll(final String type) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_INFO_TYPE, type);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynClearAll))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resClear = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resClear.getCode())) {
                            switch (type) {
                                case "comment":
                                    ((NewsCommentFragment) fragments.get(0)).clearAll();
                                    break;
                                case "notification":
                                    ((NewsNoticeFragment) fragments.get(1)).clearAll();
                                    break;
//                                case "invite":
//                                    ((NewsInviteFragment) fragments.get(2)).clearAll();
//                                    break;
                            }
                            showToast("清除成功");
                        } else {
                            showToast(resClear.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", "drawable", "com.github.postsanf.skinby")));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yn_title_color", "color", "com.github.postsanf.skinby")));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", "com.github.postsanf.skinby")));
                mTabLayout.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yn_title_color", "color", "com.github.postsanf.skinby")));
                for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                    TextView tv = new TextView(this);
                    tv.setText(mTabLayout.getTabAt(i).getText());
                    tv.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", "com.github.postsanf.skinby")));
                    mTabLayout.getTabAt(i).setCustomView(null);
                    mTabLayout.getTabAt(i).setCustomView(tv);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
    }

    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "消息中心_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }

}

